package org.xfy.ymcc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.xfy.ymcc.domain.Permission;
import org.xfy.ymcc.service.IPermissionService;

import java.util.List;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private IPermissionService permissionService;

    //提供用户信息，这里没有从数据库查询用户信息，在内存中模拟
//    @Bean
//    public UserDetailsService userDetailsService(){
//        InMemoryUserDetailsManager inMemoryUserDetailsManager =
//        new InMemoryUserDetailsManager();
//        inMemoryUserDetailsManager.createUser(User.withUsername("zs").password("123").authorities("admin").build());
//        return inMemoryUserDetailsManager;
//    }


    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder() {
//        return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }

    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //去查询所有权限
        List<Permission> list = permissionService.list();

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry = http.formLogin()                              //允许表单登录
                .successForwardUrl("/loginSuccess")             // 设置登陆成功页 前后端分离项目一般不会用
                .and().authorizeRequests()
                .antMatchers("/login").permitAll(); //登录路径放行 应该也设置一个数据集放所有需要放行的路径
        list.forEach(permission -> {
            //授权配置 循环取出数据库的数据
            expressionInterceptUrlRegistry.antMatchers(permission.getResource()).hasAuthority(permission.getSn());
        });
        expressionInterceptUrlRegistry//需要什么权限

                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查  可以提供效率
    }
}